const gulp = require('gulp')
const htmlMin = require('gulp-htmlmin')
const cssMin = require('gulp-cssmin')
const sass = require( 'gulp-sass' ) ( require ( 'sass' ) )
const uglify = require('gulp-uglify')
const babel = require('gulp-babel')
const del = require('del')
const server = require('gulp-webserver')

const htmlHandler = function(){
    return gulp.src('./src/**/*.html')
    .pipe(htmlMin({
         removeComments: true,//清除HTML注释
           collapseWhitespace: true,//压缩HTML
           collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input 		checked />
         removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
        //  removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
         removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
         minifyJS: true,//压缩页面JS
         minifyCSS: true//压缩页面CSS 
    }))
    .pipe(gulp.dest('./dist'))
}
const cssHandler = ()=> {
    return gulp.src('./src/sass/*.scss')
    .pipe(sass())
    .pipe(cssMin())
    .pipe(gulp.dest('./dist/css'))
}
const jsHandler = ()=>{
    return gulp.src('./src/js/*.js')
    //先把ES6转成ES5代码
    .pipe(babel({
        presets: ['es2015']
    }))
    //再进行压缩处理
    .pipe(uglify())
    .pipe(gulp.dest('./dist/js'))
}
const libsHandler = ()=>{
    return gulp.src('./src/libs/**')
    .pipe(gulp.dest('./dist/libs'))
}
const imgHandler = ()=>{
    return gulp.src('./src/img/**')
    .pipe(gulp.dest('./dist/img'))
}
const jsonHandler = ()=>{
    return gulp.src('./src/api/**')
    .pipe(gulp.dest('./dist/api'))
}
const delHandler = function(){
    return del(['./dist/'])
}
const serverHandler = function () {
    return gulp
        .src('./dist')
        .pipe(server({
            host: 'localhost',          // 配置打开浏览器的域名
            port: 9500,                 // 配置打开浏览器的端口号
            livereload: true,           // 自动刷新浏览器
            open: '/index.html'  // 默认打开 dist 文件夹下的哪个文件
        }))
}
const watchHandler =  function () {
    gulp.watch('./src/sass/**', cssHandler) 
    gulp.watch('./src/js/**', jsHandler)
    gulp.watch('./src/**/*.html', htmlHandler)
    gulp.watch('./src/libs/**', libsHandler)
    gulp.watch('./src/img/**', imgHandler)
}

module.exports.default = gulp.series(
    delHandler,
    gulp.parallel(htmlHandler,cssHandler,jsHandler,libsHandler,imgHandler,jsonHandler),
    serverHandler,
    watchHandler
)